package com.jiezuo.flowable.listener;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jiezuo.common.util.StringUtil;
import com.jiezuo.common.utils.SpringUtil;
import com.jiezuo.flowable.mapper.CommonMapper;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.impl.context.Context;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @description 领导会签审批
 * @author 庞留杰
 * @date 2025/2/22 17:34
 * @version V1.0
 **/
@Slf4j
@Component
public class MultiSignatureApprovalListener implements ExecutionListener {

    @Autowired
    CommonMapper commonMapper;

    /**
     * 来源孙晓科：四大中心发事业部的费用时，四大中心的二级部门领导审批，一级部门领导不审批直接是费用承担部门或借款部门的事业部负责人审批；
     *           事业部的发行政费用了，费用承担部门由职能部门的一级部门负责人审批；
     *           四大中心发自己部门的行政费用了，还是由发起人所在部门的二级部门和一级部门领导审批
     *
     *  分析：1.四大中心发起的，有发起人的二级部门审批（发起人一级部门不用审批），之后有费用一级部门会签
     *       2.检测部门发起的，由费用一级部门会签
     * */
    @Override
    public void notify(DelegateExecution execution) {
        String processInstanceId = execution.getProcessInstanceId();
        CommonMapper commonMapper = SpringUtil.getObject(CommonMapper.class);
        RuntimeService runtimeService = Context.getProcessEngineConfiguration().getRuntimeService();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        String startUserId = processInstance.getStartUserId();//申请人
        Map<String, Object> info = commonMapper.findInfoByStartUserId(startUserId);
        Boolean is_test = "1".equals(String.valueOf(info.get("is_test")));
        Boolean is_centre = "1".equals(String.valueOf(info.get("is_centre")));
        String level = String.valueOf(info.get("level"));
        String main_dept = String.valueOf(info.get("main_dept"));
        String second_level_leader = String.valueOf(info.get("main_leader"));
        // 费用报销部门
        Set<String> idSet = new HashSet<>();
        idSet.add(main_dept);
        // 材料节能幕墙第三项目部
        JSONArray self_travel = JSONArray.parseArray(execution.getVariable("self_travel") + "");//自行出行费用明细
        //[{"note":"","night_allowance_amount":0,"test_item":"","dispatch_number":"","start_stop":"","city":"","report_status":"","night_allowance_days":0,"other_amount":0,"project_name":"","toll":0,"travel_allowance_days":0,"oil":0,"report_number":"","contract_number":"","total_amount":0,"test_person":"","test_depart":"","kilometre":0,"travel_allowance_amount":0,"test_number":"","total_days":""}]
        for (Object o : self_travel) {
            JSONObject obj = (JSONObject) o;
            String test_depart = String.valueOf(obj.get("test_depart"));
            if(StringUtil.isNotEmpty(test_depart)){
                idSet.add(test_depart);
            }
        }
        JSONArray bus_travel = JSONArray.parseArray(execution.getVariable("bus_travel") + "");//公车出行费用明细
        // [{"note":"","night_allowance_amount":0,"test_item":"主体结构常规检测","dispatch_number":"","start_stop":"","city":"","report_status":"","night_allowance_days":0,"other_amount":0,"project_name":"","toll":0,"Noamount":0,"travel_allowance_days":0,"oil":0,"report_number":"","contract_number":"","test_person":"","total_amounta":0,"total_days":"","test_depart":"311","kilometre":0,"travel_allowance_amount":0,"test_number":""},{"note":"","night_allowance_amount":0,"test_item":"预制混凝土衬砌管片","dispatch_number":"","start_stop":"","city":"","report_status":"","night_allowance_days":0,"other_amount":0,"project_name":"","toll":0,"Noamount":0,"travel_allowance_days":0,"oil":0,"report_number":"","contract_number":"","test_person":"","total_amounta":0,"total_days":"","test_depart":"318","kilometre":0,"travel_allowance_amount":0,"test_number":""}]
        for (Object o : bus_travel) {
            JSONObject obj = (JSONObject) o;
            String test_depart = String.valueOf(obj.get("test_depart"));
            if(StringUtil.isNotEmpty(test_depart)){
                idSet.add(test_depart);
            }
        }
        if (idSet.size() > 0) {
            List<String> ids = new ArrayList<>(idSet);
            List<String> first_level_leader = commonMapper.findFirstLevelDepartByIds(ids);
            execution.setVariable("first_level_leader", first_level_leader);
        }
        //是否跳过二级部门
        Boolean is_skip_second_depart = true;
        if (is_test) {//检测部门
            // 上面已经设置first_level_leader
        } else if (is_centre) {//四大中心
            if ("1".equals(level)) {//是一级部门
                // 上面已经设置first_level_leader
            } else {//不是一级部门，需二级部门审核
                is_skip_second_depart = false;
                execution.setVariable("is_skip_second_depart_2", is_skip_second_depart);
                execution.setVariable("second_level_leader", second_level_leader);
            }
        } else {
            // 上面已经设置first_level_leader
        }
        execution.setVariable("is_skip_second_depart_2", is_skip_second_depart);
    }

}
